package com.takeeasy.platform.delegate;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.MethodUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.takeeasy.platform.action.IAction;
import com.takeeasy.platform.cache.CurrentThreadPool;
import com.takeeasy.platform.cache.SystemDataCache;
import com.takeeasy.platform.dataobject.RequestDataObject;
import com.takeeasy.platform.dataobject.ResponseDataObject;
import com.takeeasy.platform.util.URLUtil;

public class BizDelegate {
	private static final Logger logger = LoggerFactory.getLogger(BizDelegate.class);

	public static ResponseDataObject delegate(RequestDataObject request) {
		String requestUri = request.getRequestURI();
		logger.debug("Request Uri:" + requestUri + ",Method:" + request.getRequestMethod());
		Map<String, String> actionInfoConfig = URLUtil.GET_ACTION_INFO(requestUri);
		logger.debug("获取到URI信息：" + actionInfoConfig);
		CurrentThreadPool.setActionInfoConfig(actionInfoConfig);
		IAction action = null;
		Object resp = null;
		try {
			Class<? extends IAction> actionName = SystemDataCache.ACTION_CACHE.get(SystemDataCache.DEFAULT_ACTION_DOMAIN).get(
					actionInfoConfig.get(URLUtil.ACTION_NAME));
			if (actionName == null) {
				ResponseDataObject respError = new ResponseDataObject();
				respError.setErrorString("无法获取有效的业务信息！ActionName:" + actionInfoConfig.get(URLUtil.ACTION_NAME));
				resp = respError;
				return (ResponseDataObject) resp;
			}
			action = actionName.newInstance();
			resp = MethodUtils.invokeMethod(action, actionInfoConfig.get(URLUtil.ACTION_METHOD_NAME), new Object[] { request },
					new Class[] { RequestDataObject.class });
			return (ResponseDataObject) resp;
		} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
			if (resp == null) {
				ResponseDataObject respError = new ResponseDataObject();
				respError.setErrorString("服务器错误！请联系软件提供商或者查看系统日志！");
				resp = respError;
			}
			logger.error(e.getMessage());
		} finally {
			if (action != null) {
				action.closeConnection();
			}
		}
		return (ResponseDataObject) resp;
	}
}
